<?php

// +----------------------------------------------------------------------
// | Static Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2024 ThinkAdmin [ thinkadmin.top ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-static
// | github 代码仓库：https://github.com/zoujingli/think-plugs-static
// +----------------------------------------------------------------------

namespace app\index\controller;

use app\event\UserRegisteredEvent;
use app\model\News;
use app\service\MailService;
use app\service\QService;
use think\admin\Controller;
use think\facade\Event;
use think\facade\Config;
use WeChat\Oauth;
use think\facade\Queue;
use app\service\SiteService;
use think\facade\Db;
use think\facade\Request;
use think\facade\Log;

class Index extends Base
{

    public function __construct(SiteService $service)
    {

        $this->service = $service;
    }

    public function index()
    {
        $code=$_SERVER["QUERY_STRING"];
        $code=str_replace('code=','',$code); 

         
        if(!empty($code)){
            return redirect(url('qq_callback', ['code' => $code]));
        }


        $news = new News();

        //开始推荐
        $click = Db::name('xj_news')
                ->alias('n')
                ->join('xj_member m', 'n.mid = m.uid') // 关联用户表
                ->field('n.id, n.title, n.add_time, n.mid, m.avatar') // 同时获取用户头像
                ->where(['n.status' => 1])
                ->order('n.click', 'desc')
                ->limit(4)
                ->select()
                ->toArray();

        //散文
        $sanwen= $news->field('id,title')->where(array('cid'=>2,'status'=>1))->order("id desc")->limit(30)->select()->toArray();
        $sanwen1 = Db::name('xj_news')
                    ->field('id, title, img_url') // 直接获取图片路径
                    ->where([
                        'cid' => 2,
                        'status' => 1,
                        'is_recommend' => 1
                    ])
                    ->where('img_url','!=','')
                    ->order('id', 'desc')
                    ->limit(2)
                    ->select()
                    ->toArray();

        //诗歌
        $shige=$news->field('id,title')->where(array('cid'=>3,'status'=>1))->order("id desc")->limit(30)->select()->toArray();
        $shige1 = Db::name('xj_news')
                ->alias('n')
                ->leftJoin('xj_images i', 'n.image_id = i.id')  // 使用左连接确保即使没有图片也能返回文章
                ->field('n.id, n.title, n.image_id, i.savepath as images')  // 直接获取图片路径并命名为images
                ->where([
                    'n.cid' => 3,
                    'n.status' => 1,
                    'n.is_recommend' => 1
                ])
                ->order('n.id', 'desc')
                ->limit(2)
                ->select()
                ->toArray();

        //杂文(后面几个栏目)
        $map['cid']= array('in','4,5,58');
        $map['status']=1;
        $zawen=$news->field('id,title')->where($map)->order("id desc")->limit(30)->select()->toArray();
        $map1['cid']= array('in','4,5,58');
        $map1['status']=1;
        $map1['is_recommend']=1;
        $zawen1 = Db::name('xj_news')
                ->alias('n')
                ->leftJoin('xj_images i', 'n.image_id = i.id')  // 使用左连接
                ->field('n.id, n.title, n.image_id, i.savepath as images')  // 直接获取图片路径
                ->where($map1)  // 保持原有查询条件
                ->order('n.id', 'desc')
                ->limit(2)
                ->select()
                ->toArray();

        //网友推荐的诗歌
        $this->recommend=$news->field('id,title')->where(array('cid'=>3,'status'=>1,'is_recommend'=>1))->order("id desc")->limit(20)->select();
        //访问量榜
        $this->access=$news->field('id,title,add_time')->where(array('status'=>1))->order("access desc")->limit(18)->select();
        //最新发布的文章
        $this->news=$news->field('id,title,add_time')->where(array('status'=>1))->order("id desc")->limit(18)->select();
        //点赞最高的文章
        $this->like=$news->field('id,title')->where(array('status'=>1,'is_recommend'=>1))->order("access desc")->limit(18)->select();
        //友情链接
        $this->link=Db::table('xj_link')->where(array('display'=>1))->order("sort desc")->select();

        $this->assign("click", $click);
        $this->assign("sanwen", $sanwen);
        $this->assign("sanwen1", $sanwen1);
        $this->assign("shige", $shige);
        $this->assign("shige1", $shige1);
        $this->assign("zawen", $zawen);
        $this->assign("zawen1", $zawen1);
        $this->siteFetch('index/index');
    }

    public function nav_list(){
        $news = new News();
        $cid = request()->param('cid');
        $this->title= Db::table('xj_category')->where('cid',$cid)->value('name');

         //编辑推荐
        $this->recommend=$news->field('id,title')->where(['status'=>1,'is_recommend'=>1])->order("id desc")->limit(10)->select();

        //访问量榜
        $this->access=$news->field('id,title')->where('status',1)->order("access desc")->limit(10)->select();
        
        //最新发布的文章
        $this->new=$news->field('id,title')->where('status',1)->order("id desc")->limit(10)->select();

        $list =$news->field('id,title,add_time,content')->where(['cid'=>$cid,'status'=>1])->order("id desc")->paginate(10);
        $list->appends(request()->get());
        $this->assign("list", $list); 
        $this->siteFetch('index/lists');
    }


    //内容
    public function article(){
        $id = request()->param('id');
        $news = new News();
        $accessKey = 'access'.$id;

        $access = cookie($accessKey);
        if(empty($access)){
            $news->where('id', $id)->inc('access')->update();
        }

        $list= $news->field('id,title,add_time,content,mid,aid,like,cid')->where('id',$id)->find();
        $penname= Db::table('xj_member')->where('uid',$list['mid'])->value('penname');
        $list['penname']= $penname;

        //编辑推荐
        $this->recommend=$news->field('id,title')->where(['status'=>1,'is_recommend'=>1])->order("id desc")->limit(10)->select();

        //访问量榜
        $this->access=$news->field('id,title')->where('status',1)->order("access desc")->limit(10)->select();
        
        //最新发布的文章
        $this->new=$news->field('id,title')->where('status',1)->order("id desc")->limit(10)->select();

        //作者的数据
        $author=Db::table('xj_member')->field('uid,penname,intr,avatar')->where('uid',$list['mid'])->find();

        //关注
        $user= session('member');
        $follow = [];
        if(!empty($user)){
            $follow= Db::table('xj_follow')->where(['one'=>$user['uid'],'tow'=>$author['uid'],'status'=>1])->find();
        }
        $comment = Db::table('xj_comment')
                ->alias('c')
                ->leftJoin('xj_member critic', 'c.critic_id = critic.uid')
                ->leftJoin('xj_member author', 'c.author_id = author.uid')
                ->field('c.*, 
                    IFNULL(critic.avatar, "/static/images/default_avatar.jpg") as avatar,
                    IFNULL(author.nickname, "匿名用户") as nickname')
                ->where(['c.pid' => $id])
                ->order('c.id', 'desc')
                ->limit(10)
                ->select()
                ->toArray();


        // 上一页
        $upwhere = [
            'cid' => $list['cid'],
            'status' => 1
        ];
        $this->up = $news->field('id,title')
            ->where('id', '<', $id)
            ->where($upwhere)
            ->order('id', 'desc')
            ->find();

        // 下一页
        $nextwhere = [
            'cid' => $list['cid'],
            'status' => 1
        ];
        $this->next = $news->field('id,title')
            ->where('id', '>', $id)
            ->where($nextwhere)
            ->order('id', 'asc')
            ->find();
        //$sql = Db::getLastSql();
        //echo $sql;
       // print_r($follow);
        cookie($accessKey,$id,86400);
        $this->assign("author", $author);
        $this->assign("follow", $follow);
        $this->assign("comment", $comment); 
        $this->assign("list", $list); 
        $this->siteFetch('index/article');
    }

    //三行情诗
    public function love()
    {
        $list = Db::table('xj_love')
            ->alias('l')
            ->leftJoin('xj_member m', 'l.mid = m.uid')
            ->field('l.*, IFNULL(m.penname, "匿名用户") as penname') // 设置默认笔名
            ->where(['l.status'=>1])
            ->order('l.likes', 'desc')
            ->paginate(10);
        $this->assign("list", $list); 
       $this->siteFetch('index/love');
    }

    //三行情诗点赞
    public function loveLike(){
        $like_id = request()->param('id');
        $ntime = date('Y-m-d',time());
        
        $ip = Request::ip();
        $ip_info = Db::table('xj_love_ip')->where(array('ip'=>$ip,'like_id'=>$like_id,'add_time'=>$ntime))->find();
        if(!empty($ip_info)){
            if($ip_info['add_time'] == $ntime){
                return arrayFail('客官，,你今天已经点赞了！！！');
            }
                
        }
        try {
        // 开始事务
        Db::startTrans();
        
            // 1. 记录IP信息
            $ipResult = Db::table('xj_love_ip')->insert([
                'ip'       => $ip,
                'num'      => 1,
                'like_id'  => $like_id,
                'add_time' => $ntime
            ]);

            // 2. 点赞数+1
            $likeResult = Db::table('xj_love')
                          ->where('id', $like_id)
                          ->inc('likes')
                          ->update();
            
            // 提交事务
            Db::commit();
            
            return arraySuccess('客官,哟哟,点击成功了!!!');
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return arrayFail('[捂脸],点击失败了！！！');
        }
        
    }

    //用户登录处理
     public function login(){
        $name = request()->param('username');
        $password = request()->param('password');
        if(empty($name)){
            return arrayFail('客官，,这货账号为空了！！！');
        }
        if(empty($password)){
            return arrayFail('客官，,这货密码为空了！！！');
        }
        $row= Db::table('xj_member')->where('nickname',$name)->find();
        if(empty($row)){
            return arrayFail('客官，,这货把账号写错咯！！！');
        }
        if (!password_verify($password, $row['pwd'])){
            return arrayFail('客官，,这货把密码写错咯');
        }
        $data['login_time']= date('Y-m-d H:i:s');
        $data['login_ip'] = Request::ip();
        Db::table('xj_member')->where('nickname',$name)->update($data);

        $session_member = [
            'uid' => $row['uid'],
            'nickname' => $row['nickname'],
            'avatar' => $row['avatar'],
        ];
        session('member',$session_member);
        return arraySuccess('客官,本宝宝等你很久了!!!');
     }

     //qq登录
     public function qq_login(){
         $authUrl = (new QService())->qqLogin();
         return redirect($authUrl);
     }

    // 处理回调
    public function qq_callback() {
        $code = request()->param('code');
        $datas = (new QService())->callback($code);
        $openid = isset($datas['openid'])? $datas['openid']:'';
        $user_info = $datas['userInfo'];
        Log::channel('schedule')->info($datas);
        $member_info = Db::table('xj_member')->where('openid',$openid)->find();
        if(empty($member_info)){
            //第一次登录
            $data['nickname']=$user_info['nickname'];
            $data['penname']=$user_info['nickname'];
            $data['avatar']=$user_info['figureurl'];
            $data['openid']=$openid;
            $data['login_time']=date('Y-m-d H:i:s');
            $data['login_ip'] = Request::ip();
            $uid = Db::table('xj_member')->insertGetId($data);
            $session_member = [
                'uid' => $uid,
                'nickname' => $data['nickname'],
                'avatar' => $data['avatar'],
            ];
        }else{
            $data_login['login_time'] = date('Y-m-d H:i:s');
            $data_login['login_ip'] = Request::ip();
            Db::table('xj_member')->where('openid',$openid)->update($data_login);
            $session_member = [
                'uid' => $member_info['uid'],
                'nickname' => $member_info['nickname'],
                'avatar' => $member_info['avatar'],
            ];
        }
        session('member',$session_member);
        return redirect('http://www.okshiwen.cn/');
    }

     //用户注册处理
     public function reg(){
        $name = request()->param('username');
        $password = request()->param('password');
        if(empty($name)){
            return arrayFail('客官，,这货账号为空了！！！');
        }
        if(empty($password)){
            return arrayFail('客官，,这货密码为空了！！！');
        }

        $row= Db::table('xj_member')->where('nickname',$name)->find();
        if(!empty($row)){
            return arrayFail('客官，,这这个垃圾账号被别人霸占了！！！');
        }
        //$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $data = [
            'nickname' => $name,
            'pwd' => password_hash($password, PASSWORD_DEFAULT),
            'reg_date' => time(),
            'login_ip' => Request::ip(),
            'login_time' => date('Y-m-d H:i:s'),
        ];
        $res = Db::table('xj_member')->insertGetId($data);
        if(!$res){
            return arrayFail('客官，,遇到了不明飞行物，失败了！！！');
        }
        $session_member = [
            'uid' => $res,
            'nickname' => $data['nickname'],
        ];
        session('member',$session_member);
        return arraySuccess('客官,本宝宝等你很久了!!!');
     }

       //注销用户
    public function logout(){
        session('member',null);
        return arraySuccess('客官,这货终于走了!!!');
    }

    //文章分享
    public function share(){
        $pid = request()->param('pid');
        $share = request()->param('share');
        $sharenum = empty($share)?0:$share;
        $data = [
            'id'=> $pid,
            'sharenum'=> $sharenum,
        ];
        Db::table('xj_news')->where('id',$data['id'])->update($data);
     }

     //点赞
     public function like(){
        $pid = request()->param('pid');
        // 简单累加点赞数
        Db::table('xj_news')->where('id', $pid)->inc('like')->update();
        return arraySuccess('哟哟,点击成功了!!!');
     }

     //评论处理
    public function comment(){
        $pid = request()->param('pid');
        $is_level = request()->param('is_level');
        $content = request()->param('content');
        $author_id = request()->param('author_id');
        $member=session('member');
        if($author_id==$member['uid']){
            return arrayFail('自己不能评论自己');       
        }
        $data['critic']=$member['nickname'];
        $data['content']=$content;
        $data['status']=0;
        $data['addtime']=date('Y-m-d H:i:s');
        $data['pid']=$pid;
        $data['title']= Db::table('xj_news')->where('id',$pid)->value('title');
        $data['author_id']=$author_id;
        $data['critic_id']=$member['uid'];
        $data['is_level']=$is_level;
        $res= Db::table('xj_comment')->insertGetId($data);
        if(!$res){
            return arrayFail('评论失败');
        }
        return arraySuccess('评论成功，正在审核中....');
    }

    //关注
    public function follow(){
        $my_id = request()->param('my_id');
        $author_uid = request()->param('author_uid');
        $data['one']= $my_id;
        $data['tow']= $author_uid;
        $data['addtime']=date('Y-m-d H:i:s');
        $data['status']=1;
        $follow = Db::table('xj_follow')->where(['one'=>$data['one'],'tow'=>$data['tow']])->find();
        if($follow){
            $data1['status']=1;
            $data1['addtime']=date('Y-m-d H:i:s');
            $c= Db::table('xj_follow')->where(['one'=>$data['one'],'tow'=>$data['tow']])->update($data1);
        }else{
            $c= Db::table('xj_follow')->insert($data);
        }
        if(!$c){
            return arrayFail('客官,这货不让你关注!!!');
        }
        return arraySuccess('客官,这货关注成功了!!!');
    }

    //取消关注
    public function delfollow(){
        $my_id = request()->param('my_id');
        $author_uid = request()->param('author_uid');

        if($author_uid==$my_id){
            return arrayFail('客官，这家伙是你自己啊!!!');
        }
        $res = Db::table('xj_follow')->where(['one'=>$my_id,'tow'=>$author_uid])->update(['status'=>0]);
        if(!$res){
            return arrayFail('客官，这家伙舍不得你啊!!!');
        }
        return arraySuccess('客官，这家伙已经离开你了!!!');
    }

    public function sendTest()
    {
        try {
            $result = MailService::send(
                'gongxin@baiyishequ.com', // 收件邮箱
                '测试邮件主题',           // 邮件主题
                '<h1>这是一封测试邮件</h1><p>邮件内容...</p>', // HTML内容
                true                    // 是否为HTML
            );

            return json([
                'code' => 1,
                'msg' => '邮件发送成功',
                'data' => $result
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => $e->getMessage()
            ]);
        }
    }


    public function ok()
    {
        //(new Oauth())->getOauthRedirect();
        //print_r(Config::get('event'));die;
        //$this->app->event->trigger('PluginAdminChangePassword', [
        //    'uuid' => intval($user['id']), 'pass' => $data['password']
        //]);
        // 手动注册监听器（如果配置文件未加载）
        //Event::listen('app\event\UserRegisteredEvent', 'app\listener\UserRegisteredListener');
        // 用户注册逻辑
        $userId = 123; // 假设用户注册成功，获取用户ID
        // 触发用户注册事件
        Event::trigger(new UserRegisteredEvent($userId));
        //event(new UserRegisteredEvent($userId));
        return '注册成功';
    }
}
